<template>
  <div class="main user-layout-register user-layout-register-form">
    <p class="login-title">微信绑定</p>
    <a-form ref="formRegister" :form="form" id="formRegister">
      <a-form-item>
        <a-input autocomplete="false" size="large" placeholder="11 位手机号"
          v-decorator="['mobile', { rules: [{ required: true, message: '请输入正确的手机号', pattern: /^1[3456789]\d{9}$/ }, { validator: this.handlePhoneCheck }], validateTrigger: ['change', 'blur'] }]">
          <a-select slot="addonBefore" size="large" defaultValue="+86">
            <a-select-option value="+86">+86</a-select-option>
          </a-select>
        </a-input>
      </a-form-item>
      <a-row :gutter="16">
        <a-col class="gutter-row" :span="16">
          <a-form-item>
            <a-input size="large" autocomplete="false" type="text" placeholder="验证码"
              v-decorator="['captcha', { rules: [{ required: true, message: '请输入验证码' }] }]">
              <a-icon slot="prefix" type="mail" :style="{ color: 'rgba(0,0,0,.25)' }" />
            </a-input>
          </a-form-item>
        </a-col>
        <a-col class="gutter-row" :span="8">
          <a-button class="getCaptcha" size="large" :disabled="state.smsSendBtn" @click.stop.prevent="getCaptcha"
            v-text="!state.smsSendBtn && '获取验证码' || (state.time + ' s')"></a-button>
        </a-col>
      </a-row>
      <a-form-item>
        <div class="bind-box">
          <a-button size="large" type="primary" htmlType="submit" class="register-button" :loading="registerBtn"
            @click.stop.prevent="handleSubmit" :disabled="registerBtn">绑定
          </a-button>
          <div>
            <router-link class="login" :to="{ name: 'register' }">注册</router-link>
            <span style="padding:0 10px;">/</span>
            <router-link class="login" :to="'/'">使用已有账户登录</router-link>
          </div>
        </div>
      </a-form-item>
    </a-form>
  </div>
</template>

<script>
import { mixinDevice } from '@/utils/mixin.js'
import { getSmsCaptcha, wechatBind } from '@/api/login'
import { settingInfo } from '@/api/system/system'
import Vue from 'vue'
import { ACCESS_TOKEN, TENANTID } from '@/store/mutation-types'

export default {
  name: 'BindWechat',
  components: {
  },
  mixins: [mixinDevice],
  data() {
    return {
      form: this.$form.createForm(this),

      state: {
        time: 60,
        smsSendBtn: false,
        passwordLevelChecked: false,
        percent: 10,
        progressColor: '#FF0000'
      },
      registerBtn: false,
      code: '',
      noSead: true
    }
  },
  created() {
    this.getSettingInfo()
  },
  activated() {
    this.form.resetFields()
  },
  computed: {
  },
  methods: {
    showDialog() {
      this.$refs.dialog.show()
    },

    handlePhoneCheck(rule, value, callback) {
      callback()
    },

    handlePasswordInputClick() {
      if (!this.isMobile()) {
        this.state.passwordLevelChecked = true
        return
      }
      this.state.passwordLevelChecked = false
    },

    handleSubmit() {
      const { form: { validateFields }, state, $router } = this
      validateFields({ force: true }, (err, values) => {
        if (!err) {
          state.passwordLevelChecked = false
          if (this.noSead) {
            this.$message.error('请获取验证码!')
            return false
          }
          var data = {
            phoneNumber: values.mobile,
            verificationCode: values.captcha,
            socialUserId: this.$route.query.socialUserId
          }
          return wechatBind(data)
            .then(res => {
              if (res.code === 0) {
                this.$message.success('绑定成功!')
                Vue.ls.set(ACCESS_TOKEN, res.data.token, 12 * 60 * 60 * 1000)
                this.$store.commit('SET_TOKEN', res.data.token)
                $router.push({ path: `/` })
              } else {
                this.$message.error(res.msg)
              }
            })
          // $router.push({ name: 'registerResult', params: { ...values } })
        }
      })
    },

    getCaptcha(e) {
      e.preventDefault()
      const { form: { validateFields }, state, $message, $notification } = this

      validateFields(['mobile'], { force: true },
        (err, values) => {
          if (!err) {
            state.smsSendBtn = true

            const interval = window.setInterval(() => {
              if (state.time-- <= 0) {
                state.time = 60
                state.smsSendBtn = false
                window.clearInterval(interval)
              }
            }, 1000)

            const hide = $message.loading('验证码发送中..', 0)
            this.noSead = false
            getSmsCaptcha({ phoneNumber: values.mobile, verificationType: 4 }).then(res => {
              if (res.code === 0) {
                setTimeout(hide, 2500)
                if (res.data) {
                  this.code = res.data
                  $notification['success']({
                    message: '提示',
                    description: '验证码获取成功，您的验证码为：' + res.data,
                    duration: 8
                  })
                }
              } else {
                setTimeout(hide, 1)
                clearInterval(interval)
                state.time = 60
                state.smsSendBtn = false
                this.requestFailed(res)
              }
            }).catch(err => {
              setTimeout(hide, 1)
              clearInterval(interval)
              state.time = 60
              state.smsSendBtn = false
              this.requestFailed(err)
            })
          }
        }
      )
    },
    requestFailed(err) {
      this.$notification['error']({
        message: '错误',
        description: ((err.response || {}).data || {}).message || err.msg || '请求出现错误，请稍后再试',
        duration: 4
      })
      this.registerBtn = false
    },

    // 获取信息
    getSettingInfo() {
      return settingInfo()
        .then(res => {
          if (res.code === 0) {
            this.$store.commit('SET_CONFIG', res.data)
            if (res.data && res.data.sysTitle) {
              window.document.title = res.data.sysTitle
            }
            if (res.data && res.data.logoUrl && res.data.logoUrl.imagePathSmall) {
              document.getElementById('iconLogo').href = res.data.logoUrl.imagePathSmall
            }
          } else {
            this.$message.error(res.msg)
          }
        })
    }
  }
}
</script>
<style lang="less">
.user-register {

  &.error {
    color: #ff0000;
  }

  &.warning {
    color: #ff7e05;
  }

  &.success {
    color: #52c41a;
  }

}

.user-layout-register-form {
  background: white;
  border-radius: 8px;
  padding: 40px 60px 60px 60px;
  width: 500px;
  box-shadow: 0 6px 20px 5px rgba(40, 120, 255, 0.1), 0 16px 24px 2px rgba(0, 0, 0, 0.05);
}

.user-layout-register {
  .ant-input-group-addon:first-child {
    background-color: #fff;
  }
}
</style>
<style lang="less" scoped>
.user-layout-register {

  &>h3 {
    font-size: 16px;
    margin-bottom: 20px;
  }

  .getCaptcha {
    display: block;
    width: 100%;
    height: 40px;
  }

  .bind-box {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .register-button {
    width: 50%;
  }

  .login {
    line-height: 40px;
  }

  .login-title {
    text-align: center;
    font-size: 18px;
  }
}
</style>
